import { message } from 'antd'
import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'

interface ResponseData {
  code: number
  msg: string
  data: any
}

const http = axios.create({
  // 请求地址前缀
  baseURL: 'https://www.demo.com',
  // 请求超时时间
  timeout: 5000,
})

http.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = localStorage.getItem('token')
  if (token) {
    //Authorization专门用来携带认证信息
    //Bearer表示的是一种认证类型，表示后面携带的是一个令牌
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
})

http.interceptors.response.use((response: AxiosResponse) => {
  const res: ResponseData = response.data
  if (res.code != 200) {
    message.error(res.msg)
    return Promise.reject(new Error(res.msg))
  }
  return response.data
})

export default http
